const globalData = getApp().globalData;
import fetch from "../../utils/fetch";
const userId = globalData.userInfo.id;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentDate: '',
    ingested: 0, // 饮食摄入
    targetHeat: 1300, // 推荐摄入
    exerciseHeat: 0, // 运动消耗
    canEat: 1300, // 还能摄入或者已经超出
    nutritionData: [{
        name: '碳水化合物',
        percent: 85.22,
        weight: 125
      },
      {
        name: '蛋白质',
        percent: 14.22,
        weight: 49
      },
      {
        name: '脂肪',
        percent: 0.23,
        weight: 41
      }
    ],
    foodRecord: {},
    //饮食记录键值数组
    foodRecordKey: [],
    //删除饮食记录按钮
    slideButtons: [{
      text: '删除',
      type: 'warn',
    }],
    foodIcons: [{
        name: '早餐',
        img: '../../assets/record_icons/breakfast.png'
      },
      {
        name: '午餐',
        img: '../../assets/record_icons/lunch.png'
      },
      {
        name: '晚餐',
        img: '../../assets/record_icons/dinner.png'
      },
      {
        name: '加餐',
        img: '../../assets/record_icons/jiacan.png'
      },
      {
        name: '运动',
        img: '../../assets/record_icons/sport.png'
      }
    ],
    selectedFood: {}, // 展示用的选中食物数据
    selectedFoodRecord: {},
    show: false,
    gramCurrentNumber: 0,
    foodHeat: 0, // 弹出框总热量
    unitHeat: 0, // 选中食物的单位热量
    sportsRecord: [],
    isShow: false,
    selectedFoodRecord:{},
    selectedSport:{},
    currentNumber: 0,
    totalHeat: 0,
    unitSportHeat: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      currentDate: options.recordDate
    })
    const {
      ingested,
      canEat,
      targetHeat,
      exerciseHeat,
      nutritionData
    } = wx.getStorageSync('canvasdata');
    this.setData({
      ingested,
      canEat,
      targetHeat,
      exerciseHeat,
      nutritionData
    })
    this.initCanvas();
    this.getFoodRecord();
    this.getSportsRecord();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  enableRefresh: false, //该变量用于页面onshow重新获取食物记录数据，并且onload如果执行则不重复执行onshow
  onShow() {
    if (this.enableRefresh) {
      this.getFoodRecord();
    } else {
      this.enableRefresh = true;
    }
  },
  initCanvas() {
    const query = wx.createSelectorQuery()
    query.select('#circle').fields({
      node: true,
      size: true
    }).exec((res) => {
      const canvas = res[0].node;
      const ctx = canvas.getContext('2d');
      //获取分辨率
      this.dpr = wx.getSystemInfoSync().pixelRatio;
      //根据分辨率设置宽高
      canvas.width = res[0].width * this.dpr;
      canvas.height = res[0].height * this.dpr;
      ctx.scale(this.dpr, this.dpr);
      this.canvas = canvas;
      this.ctx = ctx;
      if (ctx) {
        this.drawCircle();
      }
    })
  },
  drawCircle() {
    const {
      ctx,
      canvas,
      dpr
    } = this;
    // 清除画布的所有内容
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    // 画内圆
    ctx.lineWidth = 2 / dpr;
    ctx.strokeStyle = "#E76F51";
    ctx.beginPath();
    // 圆心
    ctx.translate(75, 75);
    // 创建圆
    ctx.arc(0, 0, 75 - 12 / dpr, 0, 2 * Math.PI);
    // 绘制
    ctx.stroke();

    // 画外圆
    const {
      canEat,
      targetHeat,
      ingested,
      exerciseHeat
    } = this.data;
    let per = 2;
    if (canEat > 0) {
      per = 2 * (ingested) / (targetHeat + exerciseHeat);
    }

    ctx.lineWidth = 24 / dpr;
    ctx.strokeStyle = "#E76F51";
    // 设置线条末端线帽的样式
    ctx.lineCap = "round";
    ctx.beginPath();
    // 将画布的坐标系旋转90度,起点从12点位置开始
    ctx.rotate(-90 * Math.PI / 180);
    ctx.arc(0, 0, 75 - 12 / dpr, 0, per * Math.PI);
    ctx.stroke();
  },

  // 获取饮食数据
  getFoodRecord() {
    let {
      targetHeat,
      exerciseHeat
    } = this.data;
    fetch('/foodRecord/', {
      userId,
      recordDate: this.data.currentDate
    }, 'post').then(res => {
      const {
        foodRecord,
        nutritionData
      } = res.data;
      const foodRecordKey = Object.keys(foodRecord);
      let ingested = 0;
      if (foodRecordKey.length > 0) {
        foodRecordKey.forEach(item => {
          ingested += foodRecord[item].totalHeat;
          foodRecord[item].totalHeat = parseFloat(foodRecord[item].totalHeat.toFixed(2)) // 保留两位小数
          if (item == 'breakfast') {
            foodRecord[item].suggest = parseInt(targetHeat * 0.25) + ' - ' + parseInt(targetHeat * 0.30)
          } else if (item == 'lunch') {
            foodRecord[item].suggest = parseInt(targetHeat * 0.35) + ' - ' + parseInt(targetHeat * 0.40)
          } else if (item == 'dinner') {
            foodRecord[item].suggest = parseInt(targetHeat * 0.25) + ' - ' + parseInt(targetHeat * 0.30)
          } else {
            foodRecord[item].suggest = 0 + ' - ' + parseInt(targetHeat * 0.10)
          }
        })
        ingested = parseFloat(ingested.toFixed(2));
      }
      let canEat = parseFloat((targetHeat + exerciseHeat - ingested).toFixed(2));
      this.setData({
        foodRecord: foodRecord,
        foodRecordKey,
        nutritionData,
        ingested,
        canEat
      })
      this.initCanvas();
    })
  },
  getSportsRecord() {
    const {
      targetHeat,
      ingested,
      currentDate
    } = this.data;
    fetch(`/sportsrecord/list?userId=${userId}&recordDate=${currentDate}`).then(res => {
      const exerciseHeat = res.data.sumHeat
      const canEat = targetHeat + exerciseHeat - ingested;
      this.setData({
        sportsRecord: res.data.record,
        exerciseHeat,
        canEat
      })
    })
  },
  deleteFoodRecord(e) {
    const recordId = e.currentTarget.dataset.foodRecordId;
    fetch(`/foodRecord/remove?id=${recordId}`).then(res => {
      this.getFoodRecord();
    }).catch(err => {
      this.deleteFoodRecord(e);
    })
  },
  gotoRecord(e) {
    const recordTime = e.currentTarget.dataset.recordTime;
    const recordDate = this.data.currentDate;
    if (recordTime !== '运动') {
      wx.navigateTo({
        url: `../foodcate/foodcate?recordTime=${recordTime}&recordDate=${recordDate}`,
      })
    } else {
      wx.navigateTo({
        url: `../sports/sports?recordTime=${recordTime}&recordDate=${recordDate}`,
      })
    }

  },
  updateRecord(e) {
    const foodRecordIdx = e.currentTarget.dataset.foodRecordIdx;
    const foodRecordKey = e.currentTarget.dataset.foodRecordKey;
    const selectedFoodRecord = this.data.foodRecord[foodRecordKey].food[foodRecordIdx];
    const selectedFood = selectedFoodRecord.food;
    const unitHeat = selectedFood.heat_cal.split(' ')[0];
    const num = selectedFoodRecord.num;
    const foodHeat = selectedFoodRecord.heat;
    this.setData({
      selectedFoodRecord,
      selectedFood,
      show: true,
      foodHeat,
      unitHeat,
      gramCurrentNumber: num
    })
  },
  onClose() {
    this.setData({
      show: false
    })
  },
  getCurrentNumbergram(e) {
    let result = e.detail.current;
    const foodHeat = parseFloat(this.data.unitHeat * (result / 100)).toFixed(2);
    this.setData({
      foodHeat,
      gram: result,
      gramCurrentNumber: result,
    })
  },
  update() {
    const selectedFoodRecord = this.data.selectedFoodRecord;
    selectedFoodRecord.heat = this.data.foodHeat;
    selectedFoodRecord.num = this.data.gramCurrentNumber
    fetch('/foodRecord/update', {
      foodRecord: selectedFoodRecord
    }, 'post').then(res => {
      if (res.code === 200) {
        this.setData({
          show: false
        })
        this.getFoodRecord();
      }
    })
  },
  deleteSportsRecord(e){
    const recordId = e.currentTarget.dataset.sportRecordId;
    fetch(`/sportsRecord/remove?id=${recordId}`).then(res => {
      this.getSportsRecord();
    }).catch(err => {
      this.deleteSportsRecord(e);
    })
  },
  updateSportsRecord(e){
    const sportRecordIdx = e.currentTarget.dataset.sportRecordIdx;
    const selectedSportRecord = this.data.sportsRecord[sportRecordIdx];
    const selectedSport = selectedSportRecord.sports;
    this.setData({
      selectedSport,
      selectedSportRecord,
      totalHeat: selectedSportRecord.totalHeat,
      unitSportHeat: selectedSport.heat,
      currentNumber: selectedSportRecord.num,
      isShow: true
    })
  },
  onPopupClose(){
    this.setData({
      isShow: false
    })
  },
  getCurrentNumber(e){
    let result = e.detail.current;
    const unitSportHeat  = this.data.unitSportHeat;
    const totalHeat = parseFloat(((unitSportHeat / 30) * result).toFixed(2));
    this.setData({
      totalHeat,
      currentNumber: result
    })
  },
  updateSport(){
    const selectedSportRecord = this.data.selectedSportRecord;
    selectedSportRecord.totalHeat = this.data.totalHeat;
    selectedSportRecord.num = this.data.currentNumber;
    fetch('/sportsrecord/update',{
      sportsRecord: selectedSportRecord
    },'post').then(res=>{
      if(res.code === 200){
        this.setData({
          isShow: false
        })
      }
      this.getSportsRecord();
    })
  },
  gotoIndex(){
    wx.switchTab({
      url: '/pages/index/index',
    })
    // wx.navigateTo({
    //   url: '../index/index',
    // })
  }
})